﻿using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using Batman.Cms.Controllers.Weixins.Input;
using Batman.Cms.Core.Models.Mvc;
using Batman.Cms.Core.Services;
using Batman.Cms.Core.Tools;
using Batman.Cms.Domains;
using Batman.Cms.DomainServices;
using Microsoft.EntityFrameworkCore;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace Batman.Cms.Services.Weixins
{
    public class WeixinQrCodeAppSvc : ServiceBase<QrCode>
    {
        public WeixinMpAccountDomainService WeixinMpAccountDomainService { get; set; }

        public WeixinQrCodeAppSvc(IRepository<QrCode> repository, ToolBox toolBox) : base(repository, toolBox)
        {
        }

        public async Task<ResponseBase> Create(CreateQrCodeInput model)
        {
            var token = await WeixinMpAccountDomainService.GetWeixinToken(model.WeixinMpId);
            if (string.IsNullOrEmpty(token)) return new ResponseBase(false, "没找到对应的公众号");

            var actionName = model.Type == QrCodeType.临时二维码 ? QrCode_ActionName.QR_STR_SCENE : QrCode_ActionName.QR_LIMIT_STR_SCENE;

            var createQrCodeResult = await QrCodeApi.CreateAsync(token, model.ExpiredSeconds ?? 0, 0, actionName, model.ActionInfo);

            if (!string.IsNullOrEmpty(createQrCodeResult.errmsg))
            {
                return new ResponseBase(false, createQrCodeResult.errmsg);
            }

            using (var client = new WebClient())
            {
                var url = QrCodeApi.GetShowQrCodeUrl(createQrCodeResult.ticket);
                var data = client.DownloadData(url);

                var uploadResult = await Tools.UpYunTool.UploadSync(data);

                if (uploadResult.Success)
                {
                    var entity = ObjectMapper.Map<QrCode>(model);
                    entity.Url = uploadResult.Url;
                    entity.WeixinUrl = createQrCodeResult.url;
                    entity.ExpiredSeconds = createQrCodeResult.expire_seconds;
                    entity.ExpiredAt = DateTime.Now.AddSeconds(createQrCodeResult.expire_seconds);

                    Repository.Insert(entity);
                }
            }

            return new ResponseBase(true);
        }

        /// <summary>
        /// 获取二维码分页
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public PagedResultDto<QrCode> GetQrCodes(PagedResultRequestDto page)
        {
            var query = Repository.GetAll().AsNoTracking();

            return this.ToPaged(query, page, t => t.Id);
        }
    }
}
